<template>
  <BasicDrawer 
      v-bind="$attrs" @register="registerDrawer" :width="width" 
      destroyOnClose :title="getTitle" @ok="handleSubmit" :defaultFullscreen="true" showFooter>
   <MyTableAlert type="success" message="模板变量是用于消息推送时候, 在模板中使用的变量"/>
    <JVxeTable
      ref="tableRef"
      stripe
      toolbar
      keepSource
      rowNumber
      rowSelection
      asyncRemove
      dragSort
      :auto-resize="true" 
      :sync-resize="compData.activeKey"
      :maxHeight="700"
      :checkboxConfig="{range: true}"
      :disabledRows="{ isPk: [true] }"
      :loading="compData.loading"
      :disabled="false"
      :columns="compData.columns"
      :dataSource="compData.dataSource"
      @valueChange="handleValueChange"
      @removed="handleRemove"
    >
    </JVxeTable>
  </BasicDrawer>
</template>
<script lang="ts" setup>
import {computed, onUnmounted, reactive, ref, useAttrs} from 'vue';
import MyTableAlert from '/@/components/My/MyTableAlert.vue';
import {JVxeColumn} from '/@/components/jeecg/JVxeTable/types'
import {msgFieldVxeColumns} from '../task.data';
import {listMsgField, saveOrUpdateMsgField} from '../task.api';
import {useGlobSetting} from '/@/hooks/setting';
import {useMessage} from '/@/hooks/web/useMessage';
import {BasicDrawer, useDrawerInner} from '/@/components/Drawer';

// 声明Emits
const emit = defineEmits(['success', 'register']);
const attrs = useAttrs()
const taskRecord = ref<any>({})

interface CompData {
  loading: boolean;
  columns: JVxeColumn[];
  activeKey: string;
  dataSource: Recordable[];
}

const compData = reactive<CompData>({
  loading: false,
  columns: msgFieldVxeColumns,
  activeKey: '',
  dataSource: [],
})

const tableRef = ref()
const width = ref<number | string>('55%')
const { createMessage } = useMessage();
const glob = useGlobSetting();

onUnmounted(() => {
  console.log('template var component onUnmounted');
  
})
const getData = () => {
  const data = tableRef.value!.getTableData()
  return data
}

const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
  taskRecord.value = data.record
  compData.dataSource = await listMsgField({ taskId: taskRecord.value.id})
  console.log("data: ", data.record)
});

const getTitle = computed(() => `配置 ${taskRecord.value.name} 消息字段`)

const handleValueChange = (event) => {
  console.log("handleValueChange, event: ", event)
  // const data = tableRef.value!.getTableData()
  // emit("update:templateVars", data)
}

const validate = async (callback: Function) => {
  const values = tableRef.value!.getTableData()
  for(const item in values) {
    const errMap = await tableRef.value!.validateTable(values[item])
    if (errMap) {
      console.log('表单验证未通过：', { errMap });
      if (callback) {
        callback()
      }
      await tableRef.value!.validateTable()
      throw new Error(errMap);
    } 
  }
  return values
}


const handleRemove = async (event) => {
  try {
    let ids = []
    event.deleteRows.forEach(x => {
      if (!x.id.includes("row")) {
        ids.push(x.id)
      }
    })
    if (ids.length == 0) {
      return
    }
    console.log("delete ids: ", ids)
    await tableRef.value!.removeSelection();
    createMessage.success('删除成功！');
  } catch(e) {
    createMessage.warn('删除失败！');
  } finally {
    await tableRef.value!.removeSelection();
  }
}

const setDataSource = (value) => {
  compData.dataSource = value
}

//表单提交事件
async function handleSubmit() {
  setDrawerProps({ confirmLoading: true });
  try {
    await validate(() => {})
    const fieldForm = getData()
    await saveOrUpdateMsgField(taskRecord.value.id, fieldForm)
    closeDrawer();
    createMessage.success('配置成功')
  } finally {
    setDrawerProps({ confirmLoading: false });
  }
}


defineExpose({setDataSource, getData, validate})
</script>
